package com.cookor.poi.modules.weixin.open;

import com.cookor.poi.common.utils.IdGen;
import com.cookor.poi.modules.sys.utils.UserUtils;
import com.cookor.poi.modules.weixin.account.PlatformAccount;
import com.cookor.poi.modules.weixin.entity.TWeixinConfig;
import com.cookor.poi.modules.weixin.service.TWeixinConfigService;
import com.cookor.poi.utils.CacheFactory;
import com.google.common.collect.Maps;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.json.JSONObject;
import com.xiaoleilu.hutool.json.JSONUtil;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Description: TODO
 * @author: scott
 * @date: 2021年05月18日 14:29
 */
@Controller
@RequestMapping(value = "/openwx")
public class WxOpenController {

    @Autowired
    TWeixinConfigService tWeixinConfigService;

    protected static Logger logger = LoggerFactory.getLogger(WxOpenController.class);



    @RequestMapping(value = "/ticket")
    @ResponseBody
    public String wechatPlatformEvent(@RequestParam("timestamp") String timestamp,
                                                          @RequestParam("nonce") String nonce,
                                                          @RequestParam("msg_signature") String msgSignature,
                                                          @RequestBody String postData) {
        logger.info("授权事件接收URL,验证票据");
        try {
            WxOpenUtil.parsePequest(timestamp, nonce, msgSignature, postData);
            logger.info("第三方平台授权事件接收URL,验证票据成功");
        } catch (Exception e) {
            logger.error("第三方平台授权事件接收URL,验证票据异常", e.getMessage(), e);
        }
        return "success";
    }

    @RequestMapping(value = "/test")
    @ResponseBody
    public String test(String appid) {
        try {
            TWeixinConfig config = tWeixinConfigService.findByAppid(appid);
            if(config == null){
                throw new Exception("参数异常");
            }
            PlatformAccount account = new PlatformAccount(config);
            return account.getAccessToken();
        } catch (Exception e) {
            logger.error("获取token异常", e.getMessage(), e);
        }
        return "success";
    }

    @RequestMapping(value = "/oauth")
    @ResponseBody
    public String oauth() {
        try {
            return WxOpenUtil.getOauthUrl();
        } catch (Exception e) {
            logger.error("获取oauthUrl异常", e.getMessage(), e);
        }
        return "success";
    }

    @RequestMapping(value = "/oauth/success")
    @ResponseBody
    public String oauthSuccess(String auth_code, Integer expires_in) {
        if(StringUtils.isBlank(auth_code)){
            return "回调参数有误";
        }
        try {
            // 保存了公众号信息，auth_token auth_refresh_token
            PlatformAccount.getAppidByAuthCode(auth_code, IdGen.uuid());
//            WxOpenUtil.getAuthInfo(auth_code);
        }catch (Exception e){
            logger.error("获取授权信息错误", e);
            return "获取授权信息错误！";
        }
        return "success";
    }

    /*
     * 微信测试账号推送
     * */
    @RequestMapping("/push")
    @ResponseBody
    public String push(String appid)throws Exception {
        //1，配置
        Map<String, Object> params = new ConcurrentHashMap<>();
//		Account account = Account.factory(uniacid);
        params.put("touser", "obhvnsv5peOoeq6kHKHkpxlEtfrE");
        params.put("template_id","9ab2MEvAI6JPtvxk9V0jmLu-pi12UY8of1Dq8VF203c");
        params.put("url", "www.baidu.com");
        Map<String, Object> data = new ConcurrentHashMap<>();
        Map<String, Object> value = new ConcurrentHashMap<>();
        value.put("value","22");
        data.put("first", value);
        data.put("keyword1", value);
        params.put("data", data);
//        String data = "{\"touser\":\"2oBm6BwSeNEsGrZHKQLJKqGLS-ng0\",\"template_id\":\"XuziRWQCwZCW-PCGOdx83TslF6UO2m8VUpE9aJ_xGpA\",\"url\":\"http://weixin.qq.com/download\",\"topcolor\":\"#000000\",\"data\":{\"first\": {\"value\":\"尊敬的光大闽通卡客户：\",\"color\":\"#000000\"},\"headinfo\":{\"value\":\"光大银行需扣回为您车牌号111车辆所垫付的福建省高速公路通行费用10元\",\"color\":\"#000000\"},\"Date\":{\"value\":\"2015年01月10日 10:10\",\"color\":\"#000000\"},\"Type\":{\"value\":\"扣回垫款\",\"color\":\"#000000\"},\"Money\":{\"value\":\"1\",\"color\":\"#000000\"},\"remark\":{\"value\":\"交易状态：扣款成功\\n备注：扣款成功，扣款银行卡账户尾号为111\",\"color\":\"#000000\"}}}";
        TWeixinConfig config = tWeixinConfigService.findByAppid(appid);
        if(config == null){
            throw new Exception("参数异常");
        }
        PlatformAccount account = new PlatformAccount(config);
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+account.getAccessToken();
        JSONObject jsonObject = WxOpenUtil.httpPost(url, JSONUtil.toJsonStr(params));
        return jsonObject.toString();
        //httpRequest(url, "POST", data);
    }

}
